package server

import (
	"WeChatwebversion/models"
	"WeChatwebversion/utils"
	"fmt"
	"log"
	"path/filepath"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

//邮箱验证码
func Mailbox(this *gin.Context) {
		email:=this.Query("user")
		err,code:=models.SendVerificationCode(email)
		if err!=nil{
			utils.SendMessage(3,200,err.Error(),"",this)
			return
		}
		Newuser:= models.User_registration_information{
			Username: email,
			Enrollverificationcode: code,
		}
		models.Registeredusermap[email]=Newuser
		utils.SendMessage(1,200,"邮箱发送成功！","",this)
		fmt.Println(models.Registeredusermap)
		return
}
//用户注册
func Userregistration(this *gin.Context)  {
		var newuser models.User_registration_information
  		 err:=this.ShouldBind(&newuser)
		
   		if err!=nil{
			utils.SendMessage(2,200,err.Error(),"",this)
			return
		}
		//用户密码加密
		if passwrodehas,err:=utils.Passwordencryption(newuser.Userpassword);err!=nil{
			utils.SendMessage(2,200,"系统错误！请稍后重试。","",this)
		}else{ 
			//获取用户token
			usertoken,err:=utils.CreateJWT(newuser.Username);
			if err!=nil{
			utils.SendMessage(3,200,"系统错误！请稍后重试。","",this)
			return
			}
		 //拿取账号跟注册账号表进行对比是否存在重复注册

		if err:=models.UserNameID(newuser.Username,passwrodehas,usertoken);err==true{
			utils.SendMessage(2,200,"该账号已注册！","",this)
			return
		}
		if (newuser.Where_the_user_logged_in==","){
			utils.SendMessage(2,200,"请打开定位！","",this)
			return
		}
		
		//从注册列表中拿取注册信息做对比
		//注册历史信息
		Registrationhistoryinformation:=models.Registeredusermap[newuser.Username]
		fmt.Println(Registrationhistoryinformation)
		//验证码对比
		if (Registrationhistoryinformation.Enrollverificationcode=="") {
			utils.SendMessage(2,200,"验证码过期！","",this)
			return
		}
		if (Registrationhistoryinformation.Enrollverificationcode!=newuser.Enrollverificationcode) {
			utils.SendMessage(2,200,"验证码错误！","",this)
			return
		}
		
		//创建用户信息进行储存
		//编译经纬度
		addres,err:=utils.Longitude_and_latitude(newuser.Where_the_user_logged_in)
		if err!=nil{
			utils.SendMessage(3,200,"系统错误！请稍后重试。","",this)
			return
			}
		 userinformation:=models.UserInformation{
			UserToken: usertoken,
			User_name: newuser.Username,
			User_password: passwrodehas,
			User_image_ulr: "http://localhost:8088/static/acquiesce.jpg",
			User_Identity: "普通用户",
			User_login_time: time.Now().Format("2006-01-02 15:04:05"),
			Where_the_user_logged_in: addres,
			Black_list_and_whitelist: true,
			UserAccountNumber: "秋",
			AIGlossary: "秋",
		 }
		 models.MYSQL_ExtractData(&userinformation)
		 utils.SendMessage(1,200,"注册成功！",usertoken,this)
		}

		
   }
   //用户登录接口
   func Login(this *gin.Context)  {
	var newuser models.User_Login
  		 err:=this.ShouldBind(&newuser)
		
   		if err!=nil{
			utils.SendMessage(2,200,err.Error(),"",this)
			return
		}
		//编译经纬度
		addres,err:=utils.Longitude_and_latitude(newuser.Where_the_user_logged_in)
		if err!=nil{
			utils.SendMessage(3,200,"系统错误！请稍后重试。","",this)
			return
			}
		//查询账号是否存在或者正确
		val,usertoken:=models.FIndUsernameRedis(newuser.Username,newuser.Userpassword)
		switch val {
		case 1: utils.SendMessage(2,200,"该账号未注册！","",this)
				return
		case 2: utils.SendMessage(2,200,"系统错误，稍后重试！","",this)
				return
		case 3: utils.SendMessage(2,200,"密码错误！","",this)
				return
		case 4: utils.SendMessage(1,200,"登录成功！",usertoken,this)
		//修改用户登录地址
			models.MYSQL_user_address(newuser.Username,addres)
				return
		}
   }

   //查询用户基本信息
   func Login_find_userinformation(this *gin.Context)  {
	usertoken:=this.Query("usertoken")
	if usertoken==""{
		return
	}
	claims,err:=utils.DecodeJWT(usertoken)
	if err!=nil{
		log.Println(err)
	utils.SendMessage(2,200,"令牌过期！请重新登录！","",this)
	return
	}
	//数据库查询用户的基本信息
	 user,errstring:=models.FInd_userinformation(claims.Username)
		if errstring!=""{
			utils.SendMessage(2,200,errstring,"",this)
			return
		}
		utils.SendUserInformation(1,200,utils.ReturnMessageUserInformation{
			User_image_ulr: user.User_image_ulr,
			User_Identity: user.User_Identity,
			User_login_time: user.User_login_time,
			Where_the_user_logged_in: user.Where_the_user_logged_in,
			Black_list_and_whitelist: user.Black_list_and_whitelist,
			AIGlossary: strings.Split(user.AIGlossary, " "),
			UserAccountNumber: user.UserAccountNumber,
		},this)

   }
//修改用户昵称
   func EditUserName(this *gin.Context)  {
	usertoken:=this.Query("usertoken")
	username:=this.Query("username")

	if usertoken==""{
		return
	}
	claims,err:=utils.DecodeJWT(usertoken)
	if err!=nil{
		log.Println(err)
	utils.SendMessage(2,200,"令牌过期！请重新登录！","",this)
	return
	}
	err=models.Edit_MYSQL_UserName(claims.Username,username)
	if err!=nil{
		utils.SendMessage(2,200,"系统错误，稍后重试！","",this)
		return
	}
		utils.SendMessage(1,200,"修改成功!","",this)

   }

   //接收用户上次头像数据
   func UserProfilePicture(this *gin.Context)  {
	data:=this.PostForm("data")
	if data==""{
		utils.SendMessage(2,200,"警告！用户身份错误！","",this)

	}
	claims,err:=utils.DecodeJWT(data)
	if err!=nil{
		log.Println(err)
	utils.SendMessage(2,200,"令牌过期！请重新登录！","",this)
	return
	}
	// 从请求中获取上传的文件
		file, err := this.FormFile("file")
		if err != nil {
		utils.SendMessage(2,200,"未找到上传的文件","",this)
			return
		}	
		uploadDir := "./static/"
		userdirname:=claims.Username+filepath.Ext(file.Filename)
		fmt.Println(userdirname)
		// 将上传的文件保存在本地
		dst := filepath.Join(uploadDir,userdirname )
		fmt.Println(dst)
		if err := this.SaveUploadedFile(file, dst); err != nil {
					utils.SendMessage(2,200,"文件保存失败","",this)
			return
		}
        User_profile_picture:="http://localhost:8088/static/"+userdirname
		err=models.Edit_MYSQL_UserImage(claims.Username,User_profile_picture)
		if err!=nil{
		utils.SendMessage(2,200,"系统错误，稍后重试！","",this)
		return
	}
		utils.SendMessage(1,200,"修改成功!",User_profile_picture,this)
	
   }
   //修改用户黑白名单管理
   func User_List_Roll_call(this *gin.Context)  {
	usertoken:=this.Query("usertoken")
	list:=this.Query("list")
	listbool:=false
	if list=="true"{
		listbool=true
	}
	if usertoken==""{
		utils.SendMessage(2,200,"警告！用户身份错误！","",this)
		return
	}
	claims,err:=utils.DecodeJWT(usertoken)
	if err!=nil{
		log.Println(err)
	utils.SendMessage(2,200,"令牌过期！请重新登录！","",this)
	return
	}
	if err=models.List_User_Roll_call(claims.Username,listbool);err!=nil{
	utils.SendMessage(2,200,"系统错误，稍后重试！","",this)
		return
	}
	utils.SendMessage(1,200,"修改成功!","",this)
   }
   //添加或者修改AI提示词
   func AI_Trigge_Rword(this *gin.Context)  {
		usertoken:=this.Query("usertoken")
        inputvalue:=this.Query("inputvalue")
		inputtype:=this.Query("type") //1表示添加 2表示删除
		if usertoken==""{
		utils.SendMessage(2,200,"警告！用户身份错误！","",this)
		return
	}
	claims,err:=utils.DecodeJWT(usertoken)
	if err!=nil{
		log.Println(err)
	utils.SendMessage(2,200,"令牌过期！请重新登录！","",this)
	return
	}
	if inputtype=="1" {
		userinformation,errtype:=models.FInd_userinformation(claims.Username)
		if errtype!=""{
			utils.SendMessage(2,200,"系统错误，稍后重试！","",this)
			return
		}
		AI_prompt_word:=userinformation.AIGlossary+" "+inputvalue
		err:=models.AI_User_Call_Word(claims.Username,AI_prompt_word)
		if err!=nil{
			utils.SendMessage(2,200,"系统错误，稍后重试！","",this)
			return
		}
		utils.SendMessage(1,200,"添加成功!","",this)
		
	}else{
		err:=models.AI_User_Call_Word(claims.Username,inputvalue)
		if err!=nil{
			utils.SendMessage(2,200,"系统错误，稍后重试！","",this)
			return
		}
		utils.SendMessage(1,200,"删除成功!","",this)
		}
	}
   //注销账号
   func Cancel_Account(this *gin.Context)  {
	usertoken:=this.Query("usertoken")
	if usertoken==""{
		utils.SendMessage(2,200,"警告！用户身份错误！","",this)
		return
	}
	claims,err:=utils.DecodeJWT(usertoken)
	if err!=nil{
		log.Println(err)
	utils.SendMessage(2,200,"令牌过期！请重新登录！","",this)
	return
	}
	err=models.User_Cancel_Account(claims.Username)
	if err!=nil{
			utils.SendMessage(2,200,"系统错误，稍后重试！","",this)
			return
		}
	err=models.User_Cancel_Account_Redis(claims.Username)
	if err!=nil{
			utils.SendMessage(2,200,"系统错误，稍后重试！","",this)
			return
		}
	utils.SendMessage(1,200,"注销成功!","",this)

   }

   //socket连接
   func Socket(this *gin.Context)  {
	usertoken:=this.Query("usertoken")
	if usertoken==""{
		return
	}
	claims,err:=utils.DecodeJWT(usertoken)
	if err!=nil{
		log.Println(err)
	return
	}
	conn, err := utils.Upgrader.Upgrade(this.Writer, this.Request, nil)
	if err != nil {
		log.Println("WebSocket upgrade failed:", err)
		return
	}
	defer conn.Close()

	// 将新连接添加到客户端列表中
	utils.ClientsMu.Lock()
	utils.ClientsSocket[claims.Username] = conn
	utils.ClientsMu.Unlock()
 	
	
   }

   //微信
   func WeChat(this *gin.Context)  {
	usertoken:=this.Query("usertoken")
	if usertoken==""{
		utils.SendMessage(2,200,"警告！用户身份错误！","",this)
		return
	}
	claims,err:=utils.DecodeJWT(usertoken)
	if err!=nil{
		log.Println(err)
	utils.SendMessage(2,200,"令牌过期！请重新登录！","",this)
	return
	}
	models.WeChatLogin(*claims,this)
   }